﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using SuperX.Common.Log;

namespace SuperX.Common.MSG
{
    // 
    public class MsgConvert : JsonConverter
    {
        // 
        public override bool CanWrite
        {
            get
            {
                return false;
            }
        }

        // 
        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        //
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jobject = JObject.Load(reader);
            object result;
            try
            {
                Message msg = this.CreateObject(jobject, objectType);
                serializer.Populate(jobject.CreateReader(), msg);
                result = msg;
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.ToString());
                result = null;
            }
            return result;
        }

        // 
        public virtual Message CreateObject(JObject jObject, Type objectType)
        {
            string a = jObject.GetValue("ClassType", StringComparison.OrdinalIgnoreCase).ToString();
            if (a == "ValueMsg")
            {
                return new ValueMsg();
            }
            if (a == "PropertyMsg")
            {
                return new PropertyMsg();
            }
            if (a == "EventMsg")
            {
                return new EventMsg();
            }
            if (a == "CollectionMsg")
            {
                return new CollectionMsg();
            }
            return new TimeDataMsg();
        }

        // 
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
}
